package com.future.orm.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.future.orm.session.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 配置文件解析器
 *
 * @author shiyong
 * 2020/5/20 8:32
 */
public class XMLConfigBuilder {

    public Configuration parse(InputStream inputStream) throws DocumentException, PropertyVetoException, IOException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);

        // 数据库配置
        Element rootElement = document.getRootElement();
        List<Element> propertyList = rootElement.element("dataSource").elements("property");

        Properties properties = new Properties();

        for (Element element : propertyList) {
            properties.setProperty(element.attributeValue("name"), element.attributeValue("value"));
        }

        // 连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        Configuration configuration = new Configuration();
        configuration.setDataSource(comboPooledDataSource);
        configuration.setAutoCommit(Boolean.parseBoolean(properties.getProperty("autoCommit", "false")));

        // 解析Mapper文件
        List<Element> mapperList = rootElement.elements("mapper");
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);

        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream in = Resources.getResourceAsStream(mapperPath);
            xmlMapperBuilder.parse(in);
        }

        return configuration;
    }
}
